<?php

class WikiPageController extends MyController
{
    // {{{ *** Members ***
    //public $layout='column2';

    /**
     * The default action 
     * 
     * @var string
     */
    public $defaultAction = 'index';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    public $name = 'Wiki Pages';
    // }}} 
    // {{{ *** Methods ***
    // {{{ *** Actions ***
    // {{{ actionView
    /**
     * Displays a particular model.
     */
    public function actionView()
    {
        $wikiPage=$this->loadModel();

        $this->render('view',array(
            'model'=>$wikiPage,
            'show_content'=>true,
        ));
    } // }}} 
    // {{{ actionViewPopup
    public function actionViewPopup()
    {
        $this->checkAccess('user');
        $wikiPage=$this->loadModel();

        $this->renderPartial('_viewPopup',array('data'=>$wikiPage,'show_content'=>true,'popup'=>true),false,true);
    } // }}} 
    // {{{ actionExportDBChangeScript
    public function actionExportDBChangeScript()
    {
        $model = $this->loadModel();
        $schema = $model->tableSchema;
        $pk = $schema->primaryKey;
        $i=1;
        $fileName = Yii::app()->basePath.'/../sql/db_change_%03d.sql';
        while(is_file($fileName2 = sprintf($fileName,$i))) {
            $i++;
        }
        $fields = array();
        $values = array();
        foreach($model->attributes as $key => $value ) {
            if($key==$pk) continue;
            $fields[] = $key;
            $values[] = "'".str_replace(array("\r\n","\n"),array('\r\n','\n'),addslashes($value))."'";
        }
        $sql = "INSERT INTO WikiPage (".join(', ',$fields).') VALUES ('.join(', ',$values).');';
        $fp = fopen($fileName2,"wb");
        fwrite($fp, sprintf("/* V%s: WikiPage-Beitrag */\n",Yii::app()->params['version']));
        fwrite($fp,$sql);
        fclose($fp);
        $this->setFlash(
            array(
                _('WikiPage DB Change Script written'),
                sprintf(_('The file <em>%s</em> for the item <em>%s</em> has been created.'),'sql/'.basename($fileName2), $model->recordName)
            ),
            $dummy = new StdClass,
            'success'
        );
        $this->redirect(array('admin'));
    } // }}} 
    // {{{ actionCreate
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->checkAccess('wikiBookEditor');
        
        $model=new WikiPage;
        if(isset($_GET['wikiBookId']))
            $model->wikiBookId = $_GET['wikiBookId'];
        if(isset($_GET['tags']))
            $model->tags = $_GET['tags'];

        if(isset($_POST['WikiPage']))
        {
            $model->attributes=$_POST['WikiPage'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    } // }}} 
    // {{{ actionUpdate
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate()
    {
        $this->checkAccess('wikiBookEditor');
        
        $model=$this->loadModel();
        if(isset($_POST['WikiPage']))
        {
            // DEBUG echo par($_POST);
            if(isset($_POST['saveAsNew']) and $_POST['saveAsNew']==1) {
                $model = new WikiPage;
            }
            $model->attributes=$_POST['WikiPage'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    } // }}} 
    // {{{ actionDelete
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete()
    {
        $this->checkAccess('wikiBookEditor');
        
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel()->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    } // }}} 
    // {{{ actionIndex
    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $criteria=new CDbCriteria(array(
            'condition'=>'status='.WikiPage::STATUS_PUBLISHED,
            'order'=>'title',
        ));
        if(isset($_GET['tag']))
            $criteria->addSearchCondition('tags',$_GET['tag']);

        $dataProvider=new CActiveDataProvider('WikiPage', array(
            'pagination'=>array(
                'pageSize'=>Yii::app()->params['postsPerPage'],
            ),
            'criteria'=>$criteria,
        ));

        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    } // }}} 
    // {{{ actionAdmin
    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $this->checkAccess('wikiBookEditor');
        
        $model=new WikiPage('search');
        if(isset($_GET['WikiPage']))
            $model->attributes=$_GET['WikiPage'];
        $this->render('admin',array(
            'model'=>$model,
        ));
    } // }}} 
    // {{{ actionSuggestTags
    /**
     * Suggests tags based on the current user input.
     * This is called via AJAX when the user is entering the tags input.
     */
    public function actionSuggestTags()
    {
        if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
        {
            $tags=WikiPageTag::model()->suggestTags($keyword);
            if($tags!==array())
                echo implode("\n",$tags);
        }
    } // }}} 
    // {{{ actionPreview
    public function actionPreview()
    {
        $parser=new CMarkdownParser;
        $parsedText = preg_replace(array("/_ICON_NEW_/","/_ICON_EDIT_/","/_ICON_VIEW_/","/_ICON_DELETE_/"),array(ICON_NEW,ICON_EDIT,ICON_VIEW,ICON_DELETE),$_POST['WikiPage'][$_GET['attribute']]);
        $parsedText = $parser->safeTransform($parsedText);
        echo $parsedText;

    } // }}} 
    // }}} End Actions
    // {{{ Other Methods
    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel()
    {
        if($this->_model===null)
        {
            if(isset($_GET['id']))
            {
                if(Yii::app()->user->isGuest)
                    $condition='status='.WikiPage::STATUS_PUBLISHED.' OR status='.WikiPage::STATUS_ARCHIVED;
                else
                    $condition='';
                $this->_model=WikiPage::model()->findByPk($_GET['id'], $condition);
            }
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Creates a new comment.
     * This method attempts to create a new comment based on the user input.
     * If the comment is successfully created, the browser will be redirected
     * to show the created comment.
     * @param WikiPage the post that the new comment belongs to
     * @return Comment the comment instance
     */
    protected function newComment($wikiPage)
    {
        $comment=new Comment;
        if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
        {
            echo CActiveForm::validate($comment);
            Yii::app()->end();
        }
        if(isset($_POST['Comment']))
        {
            $comment->attributes=$_POST['Comment'];
            if($wikiPage->addComment($comment))
            {
                if($comment->status==Comment::STATUS_PENDING)
                    Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
                $this->refresh();
            }
        }
        return $comment;
    }
    // }}} End Other Methods
    // }}} End Methods
}
